package org.sean.contactdemo.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.Assert;

public abstract class AbstractDAO {
	
	private Connection connection;
	private static final Log log = LogFactory.getLog("log4j.logger.contactdemo");
	
	public AbstractDAO(){
		this.connection = DBInstance.getINSTANCE().getConnection();
		Assert.isNotNull(this.connection);
	}
	
	public AbstractDAO(Connection connection){
		this.connection = connection;
	}
	
	public Connection getConnection(){
		return this.connection;
	}
	
	public void releaseDBResource(ResultSet rs){
		try{
			if (rs.getStatement() != null){
				rs.getStatement().close();
			}
			if (rs != null){
				rs.close();
				rs = null;
			}
		} catch (SQLException e){
			error(e);
		}
	}
	
	public void releaseConnection(){
		if (this.connection != null){
			DBInstance.closeConnection(this.connection);
		}
	}
	
	public ResultSet getResultSetAfterQuery(String sql){
		ResultSet rs = null;
		Statement stmt = null;
		try {
			stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			error(e);
		}
		return rs;
	}
	
	public boolean excute(String sql){
		boolean bSuccess = true;
		//info(sql);
		Statement stmt = null;
		if (connection == null){
			bSuccess = false;
		} else {
			try {
				stmt = connection.createStatement();
				stmt.execute(sql);
				connection.commit();
			} catch (SQLException e){
				error(e);
				bSuccess = false;
				try {
					connection.rollback();
				} catch (SQLException e1) {
					error(e);
				}
			} finally {
				if (stmt != null){
					try {
						stmt.close();
					} catch (SQLException e) {
						error(e);
					}
				}
			}
		}
		return bSuccess;
	}
	
	public void error(Object object){
		log.error(object);
	}
	
	public void info(Object object){
		log.info(object);
	}
}
